import json

import random

import re

from django.contrib.auth import authenticate

from meiduo_mall.utils.response_code import RET
from verifications import constants

from django.shortcuts import render
from django.views import View
from django import http
from django_redis import get_redis_connection
from users.models import User


class FindPasswordChangeView(View):
    def get(self,request):
        #返回找回密码页面
        return render(request,'find_password.html')

class UserNameView(View):
    def get(self,request,username):
        #1,获取参数
        image_code = request.GET.get("text")
        image_code_id = request.GET.get("image_code_id")


        #校验参数
        #为空校验
        if not all([image_code,image_code_id]):
            return http.JsonResponse({'status':'参数不全'})
        #校验图片验证码的正确性
        redis_conn = get_redis_connection('code')

        redis_image_code = redis_conn.get('image_code_%s'%image_code_id)

        #检验正确性
        if image_code.lower() != redis_image_code.decode().lower():
            return http.JsonResponse({'status':'4001'})

        #判断用户名是否存在
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            return http.JsonResponse({'status':'401'})

        else:
            mobile = user.mobile

        return http.JsonResponse({'mobile':mobile,'status':"OK"})

class SmsCodesView(View):
    def get(self,request):
        sms_code = request.GET.get('sms_code')
        mobile = request.GET.get('mobile')
        # 发送短信验证码
        sms_code = "%06d" % random.randint(0, 999999)
        print("sms_code = %s" % sms_code)

        # 使用celery发送短信
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile, sms_code, constants.REDIS_SMS_CODE_EXPIRES / 60)
        redis_conn = get_redis_connection('code')
        # 保存到redis中
        pipeline = redis_conn.pipeline()
        pipeline.setex("sms_code_%s" % mobile, constants.REDIS_SMS_CODE_EXPIRES, sms_code)
        pipeline.setex("send_flag_%s" % mobile, constants.REDIS_SEND_FLAG_EXPIRES, True)
        pipeline.execute()

        # 4,返回响应
        return http.JsonResponse({"message": "发送成功"})

class PasswordView(View):
    def get(self,request,username):
        #获取验证码
        sms_code = request.GET.get('sms_code')
        #获取用户对象
        user = User.objects.get(username=username)
        #通过对象获取手机号码
        mobile = user.mobile
        #判断手机号是否存在
        if not mobile:
            return http.JsonResponse({'status':'404'})
        #从redis中获取验证码
        sms_code_coon = get_redis_connection('code')
        redis_sms_code = sms_code_coon.get("sms_code_%s" % mobile)
        #判断验证码是否正确
        if sms_code.lower() != redis_sms_code.lower().decode():
            return http.JsonResponse({'status':'400'})
        # 获取user_id
        user_id = user.id
        #获取access_token
        # access_token = request.COOKIE.get('csrftoken')
        context={
            'user_id':user_id,
            # 'access_token':access_token
        }
        return http.JsonResponse(context)

class NewPasswordView(View):
    def post(self,request,user_id):
        #获取参数
        data_dict = json.loads(request.body.decode())
        password = data_dict.get('password')
        password2 = data_dict.get('password2')

        #检验参数
        #1,为空校验
        if not all([password,password2]):
            return http.JsonResponse({'status':'请填写数据'})
        #2,密码是否一致
        if password != password2:
            return http.JsonResponse({'status':'404'})
        #3,判断密码格式
        if re.match(r'^[0-9A-Za-z]{8,20}$',password):
            return http.JsonResponse({'status':'400'})
        #获取对象，通过对象获取原来的密码，改密码
        user = User.objects.get(id=user_id)
        user.password=password
        user.password.save()
        return http.JsonResponse({'message':'成功'})








